(*
 * Materialien zu den zentralen
 * Abiturpruefungen im Fach Informatik ab 2012 in
 * Nordrhein-Westfalen.
 *
 * Klasse TQueue
 *
 * NW-Arbeitsgruppe: Materialentwicklung zum Zentralabitur
 * im Fach Informatik
 *
 * Version 2010-12-28
 *)

UNIT mQueue;

interface

type
  TNode = class
  private
    nextNode: TNode;
    content: TObject;
    constructor create(pObject: TObject; pNext: TNode);
    procedure setNext(pNode: TNode);
    function getContent: TObject;
    function next: TNode;
    destructor destroy; override;
  end;

  TQueue = class
  private
    head: TNode;
    tail: TNode;
  public
    constructor create; virtual;
    function isEmpty: boolean; virtual;
    procedure enqueue(pObject: TObject); virtual;
    procedure dequeue; virtual;
    function front: TObject; virtual;
    destructor destroy; override;
  end;

implementation

// TNode

constructor TNode.create(pObject: TObject; pNext: TNode);
begin
  content := pObject;
  nextNode := pNext;
end;

procedure TNode.setNext(pNode: TNode);
begin
  nextNode := pNode;
end;

function TNode.getContent: TObject;
begin
  result := content;
end;

function TNode.next: TNode;
begin
  result := nextNode;
end;

destructor TNode.destroy;
begin
  inherited destroy
end;

// TQueue

constructor TQueue.create;
begin
  head := nil;
  tail := nil;
end;

function TQueue.isEmpty : boolean;
begin
  result:= head = nil;
end;

procedure TQueue.enqueue(pObject: TObject);
var
  newNode: TNode;
begin
  if pObject <> nil then
  begin
    newNode := TNode.create(pObject,nil);
    if self.isEmpty then
    begin
      head := newNode;
      tail := newNode;
    end
    else
    begin
      tail.setNext(newNode);
      tail := newNode;
    end;
  end;
end;

procedure TQueue.dequeue;
var
  temp: TNode;
begin
  if not self.isEmpty then
  begin
    temp := head;
    head := head.next;
    temp.destroy;
  end;
end;

function TQueue.front: TObject;
begin
  if self.isEmpty then
    result := nil
  else
    result := head.getContent;
end;

destructor TQueue.destroy;
begin
  while not self.isEmpty do
    self.dequeue;
  inherited destroy;  
end;

end.
